package org.subject.controller;

import com.sun.org.apache.xpath.internal.operations.Mod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.subject.dto.MessageAndUser;
import org.subject.dto.PublishMessage;
import org.subject.entity.*;
import org.subject.service.ArticleService;
import org.subject.service.MessageService;
import org.subject.service.RegistrationService;
import org.subject.utils.DateUtil;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 竞赛信息控制器
 * Created by Administrator on 2017/4/25.
 */
@Controller
@RequestMapping(value = "/message")//  url:/模块/资源/{id}/细分
public class MessageController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MessageService messageService;
    @Autowired
    private RegistrationService registrationService;
    @Autowired
    private ArticleService articleService;

    @RequestMapping(value = "/list", method = RequestMethod.GET, produces = "text/json;charset=UTF-8")
    public String messageList(Model model, @RequestParam(value = "title", required = false) String title,
                              @RequestParam(value = "page", required = false) String currentPage) {
        logger.info("页数" + title + title);
        int pages = 1;
        Pattern pattern = Pattern.compile("[0-9]{1,9}");
        if (currentPage == null || !pattern.matcher(currentPage).matches()) {
            pages = 1;
        } else {
            pages = Integer.valueOf(currentPage);
        }
        List<MessageAndUser> messageAndUsers = messageService.queryMessageList("", title, pages);
        model.addAttribute("messageList", messageAndUsers);
        int count = messageService.queryMessageCount("", title);
        logger.info("数目：" + count);
        Page page = new Page();
        page.setTotalNumber(count);
        page.setCurrentPage(pages);
        model.addAttribute("page", page);
        model.addAttribute("title", title);
        return "list";
    }

    @RequestMapping(value = "/listPage", method = RequestMethod.GET, produces = "text/json;charset=UTF-8")
    public String messageListPage(Model model,
                                  @RequestParam(value = "page", required = false) String currentPage) {
        int pages;
        Pattern pattern = Pattern.compile("[0-9]{1,9}");
        if (currentPage == null || !pattern.matcher(currentPage).matches()) {
            pages = 1;
        } else {
            pages = Integer.valueOf(currentPage);
        }
        List<MessageAndUser> messageAndUsers = messageService.queryMessageList("", "", pages);
        model.addAttribute("messageList", messageAndUsers);
        int count = messageService.queryMessageCount("", "");
        logger.info("数目：" + count);
        Page page = new Page();
        page.setTotalNumber(count);
        page.setCurrentPage(pages);
        model.addAttribute("page", page);
        return "list";
    }

    @RequestMapping(value = "/detail", method = RequestMethod.GET, produces = "text/json;charset=UTF-8")
    public String MessageDetail(Model model, @RequestParam("messageId") String messageId, HttpServletRequest request) {
        if (messageId != null && !"".equals(messageId)) {
            Long id = Long.parseLong(messageId);
            if (request.getSession().getAttribute("user") != null) {
                User user = (User) request.getSession().getAttribute("user");
                Registration registration = registrationService.selectByMIdUid(messageId, String.valueOf(user.getUserId()));
                if (registration != null) {
                    model.addAttribute("state", registration.getRegistrationState());
                }
            }
            MessageAndUser messageAndUser = messageService.selectMUByKey(id);
            logger.info(messageAndUser.toString());
            model.addAttribute("title", messageAndUser.getMessageTitle());
            model.addAttribute("content", messageAndUser.getMessageContent());
            model.addAttribute("desc", messageAndUser.getMessageDesc());
            model.addAttribute("registerstart", DateUtil.dateToStr(messageAndUser.getRegistrationStartTime()));
            model.addAttribute("registerend", DateUtil.dateToStr(messageAndUser.getRegistrationEndTime()));
            model.addAttribute("teststart", DateUtil.dateToStr(messageAndUser.getStartTime()));
            model.addAttribute("testend", DateUtil.dateToStr(messageAndUser.getEndTime()));
            model.addAttribute("requirement", messageAndUser.getContestRequirement());
            model.addAttribute("messageid", messageAndUser.getMessageId());
            model.addAttribute("createtime", messageAndUser.getCreateTime());
            model.addAttribute("name", messageAndUser.getUserName());
            model.addAttribute("userid", messageAndUser.getUserId());
        }
        return "detail";
    }

    @RequestMapping("/publishpage")
    public String getPublishPage(Model model) {
        PublishMessage publishMessage = new PublishMessage();
        model.addAttribute("publishMessage", publishMessage);
        return "publish";
    }

    @RequestMapping(value = "/publish", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
    public String publishMessage(Model model, @ModelAttribute("SpringWeb") PublishMessage publishMessage,
                                 HttpServletRequest request) {
        logger.info(publishMessage.toString());
        Message message = new Message();
        message.setMessageTitle(publishMessage.getTitle());
        message.setMessageContent(publishMessage.getContent());
        message.setMessageDesc(publishMessage.getDesc());
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < publishMessage.getRequest().length; i++) {
            builder.append(publishMessage.getRequest()[i]);
        }
        message.setContestRequirement(builder.toString());
        message.setRegistrationStartTime(DateUtil.strToDate(publishMessage.getRegisterStart()));
        message.setRegistrationEndTime(DateUtil.strToDate(publishMessage.getRegisterEnd()));
        message.setStartTime(DateUtil.strToDate(publishMessage.getTestStart()));
        message.setEndTime(DateUtil.strToDate(publishMessage.getTestEnd()));
        message.setCreateTime(new Date());
        message.setMessageRemark("");
        User user = (User) request.getSession().getAttribute("user");
        message.setUserId(user.getUserId());
        logger.info(message.toString());
        int code = messageService.insert(message);
        logger.info("code:" + code);
        int pages = 1;
        List<MessageAndUser> messageAndUsers = messageService.queryMessageList("", "", pages);
        model.addAttribute("list", messageAndUsers);
        int count = messageService.queryMessageCount("", "");
        Page page = new Page();
        page.setTotalNumber(count);
        model.addAttribute("page", page);
        List<Article> articleList = articleService.queryArticleList("", pages);
        model.addAttribute("articleList", articleList);
        return "index";
    }

    @ModelAttribute("request")
    public List<String> requstList() {
        List<String> requstList = new ArrayList<String>();
        requstList.add("大一");
        requstList.add("大二");
        requstList.add("大三");
        requstList.add("大四");
        requstList.add("大五");
        return requstList;
    }

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public String messageListBypage(Model model, @RequestParam("page") String current, HttpServletRequest req) {
        int pages;
        Pattern pattern = Pattern.compile("[0-9]{1,9}");
        if (current == null || !pattern.matcher(current).matches()) {
            pages = 1;
        } else {
            pages = Integer.valueOf(current);
        }
        List<MessageAndUser> messageAndUsers = messageService.queryMessageList("", "", pages);
        for (MessageAndUser messageAndUser : messageAndUsers) {
            logger.info(messageAndUser.toString());
        }
        model.addAttribute("list", messageAndUsers);
        int count = messageService.queryMessageCount("", "");
        Page page = new Page();
        page.setCurrentPage(pages);
        page.setTotalNumber(count);
        model.addAttribute("page", page);
        /*List<Article> articleList = articleService.queryArticleList("", pages);
        model.addAttribute("articleList", articleList);*/
        return "messageList";
    }

    /**
     * 根据 id 删除竞赛信息
     *
     * @param model
     * @param messageId
     * @return
     */
    @RequestMapping("/delete")
    public String deleteMessage(Model model, @RequestParam("messageId") String messageId) {
        int code = messageService.deleteByPrimaryKey(Long.valueOf(messageId));
        int pages = 1;
        List<MessageAndUser> messageAndUsers = messageService.queryMessageList("", "", pages);
        model.addAttribute("messageList", messageAndUsers);
        int count = messageService.queryMessageCount("", "");
        logger.info("数目：" + count);
        Page page = new Page();
        page.setTotalNumber(count);
        model.addAttribute("page", page);
        return "list";
    }

    /**
     * 获取发布者发布竞赛历史界面
     *
     * @param model
     * @param userId
     * @return
     */
    @RequestMapping("/publishHistory")
    public String publistMessageHistory(Model model, @RequestParam("userId") String userId) {
        int pages = 1;
        List<MessageAndUser> messageAndUsers = messageService.queryMessageByUId(userId, pages);
        model.addAttribute("messageList", messageAndUsers);
        int count = messageService.queryCountByUId(userId);
        logger.info("数目：" + count);
        Page page = new Page();
        page.setTotalNumber(count);
        model.addAttribute("page", page);
        return "publishHistory";
    }

    @RequestMapping("/messageList")
    public String messageList(Model model) {
        int pages = 1;
        List<MessageAndUser> messageAndUsers = messageService.queryMessageList("", "", pages);
        model.addAttribute("list", messageAndUsers);
        int count = messageService.queryMessageCount("", "");
        Page page = new Page();
        page.setTotalNumber(count);
        model.addAttribute("page", page);
        return "messageList";
    }

    @RequestMapping("/messageByFId")
    public String messageListByFId(Model model, @RequestParam("type") String type, @RequestParam("facultyId") String facultyId) {
        logger.info(type + "-->" + facultyId);
        int pages = 1;
        List<MessageAndUser> messageAndUsers;
        if (type.equals("1")) {
            messageAndUsers = messageService.queryMessageByFId(null, pages);
            for (MessageAndUser messageAndUser : messageAndUsers) {
                logger.info(messageAndUser.toString());
            }
            model.addAttribute("messageList", messageAndUsers);
            int count = messageService.queryCountByFId(null);
            Page page = new Page();
            page.setTotalNumber(count);
            model.addAttribute("page", page);
        } else {
            messageAndUsers = messageService.queryMessageByFId(facultyId, pages);
            model.addAttribute("messageList", messageAndUsers);
            int count = messageService.queryCountByFId(facultyId);
            Page page = new Page();
            page.setTotalNumber(count);
            model.addAttribute("page", page);
        }

        return "selectContestByFId";
    }

    @RequestMapping("/publishPage")
    public String publishHistoryByPage(Model model, @RequestParam("userId") String userId, @RequestParam("page") String current, HttpServletRequest req) {
        int pages;
        Pattern pattern = Pattern.compile("[0-9]{1,9}");
        if (current == null || !pattern.matcher(current).matches()) {
            pages = 1;
        } else {
            pages = Integer.valueOf(current);
        }
        List<MessageAndUser> messageAndUsers = messageService.queryMessageByUId(userId, pages);
        model.addAttribute("messageList", messageAndUsers);
        int count = messageService.queryCountByUId(userId);
        logger.info("数目：" + count);
        Page page = new Page();
        page.setCurrentPage(pages);
        page.setTotalNumber(count);
        model.addAttribute("page", page);
        return "publishHistory";
    }
}
